/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import java.io.IOException;
import java.util.logging.Level;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import util.Constants;

/**
 *
 * @author HuyNVK
 */
public class Controller extends HttpServlet {

    static public Logger log = Logger.getLogger(Controller.class.getName());

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, Exception {
        log.info("Begin processRequest(request, response)");

        response.setContentType("text/html;charset=UTF-8");
        log.info("pageName: " + request.getParameter("pageName"));
        log.info("subPage: " + request.getParameter("subPage"));
        log.info("section: " + request.getParameter("section"));
        log.info("action: " + request.getParameter("action"));

        //Redirect to target page.
        processRedirect(request);

        //Do specific action
        processAction(request);

        //Show the page.
        doView(request, response);
    }
    
    /**
     * Choose the target page.
     */
    protected void processRedirect(HttpServletRequest request) {
        HttpSession session = request.getSession(true);
        String pageName = request.getParameter("pageName");
        String subPage = request.getParameter("subPage");
        String section = request.getParameter("section");
        String selectedItemID = request.getParameter("selectedItemID");
        String admin = request.getParameter("admin");
        String user = request.getParameter("user");
        
        if(Constants.ADMIN_PAGE_NAME.equals(pageName)) {
            if(admin == null || admin.isEmpty()) {
                subPage = Constants.LOGIN_ADMIN_PAGE_NAME;
            }
        } else if(!Constants.HOME_PAGE_NAME.equalsIgnoreCase(pageName)) {
            if(user == null || user.isEmpty()) {
                pageName = Constants.LOGIN_USER_PAGE_NAME;
            }
        }
        
        session.setAttribute("pageName", pageName);
        session.setAttribute("subPage", subPage);
        session.setAttribute("section", section);
        session.setAttribute("selectedItemID", selectedItemID);
        log.info("processRedirect to: pageName=" + pageName + "; subPage=" + subPage + 
                "; section=" + section + "; selectedItemID=" + selectedItemID);
    }

    /**
     * Process committed action on target page.
     */
    protected void processAction(HttpServletRequest request) throws Exception {
        String action = request.getParameter("action");
        
        //If action is set, do this action.
        if ((action != null) && !("".equals(action))) {
            String pageName = request.getParameter("pageName");

            if (Constants.HOME_PAGE_NAME.equalsIgnoreCase(pageName)) {
                processActionHomePage(request);
            } else if (Constants.ADMIN_PAGE_NAME.equalsIgnoreCase(pageName)) {
                processActionAdminPage(request);
            } else if (Constants.DEFECT_LOG_PAGE_NAME.equalsIgnoreCase(pageName)) {
                defectLogController.processAction(request);
            } else if (Constants.TEAMMATE_PAGE_NAME.equalsIgnoreCase(pageName)) {
                processActionTeammatePage(request);
            } else if (Constants.PROFILE_PAGE_NAME.equalsIgnoreCase(pageName)) {
                processActionProfilePage(request);
            } else if (Constants.LOGIN_USER_PAGE_NAME.equalsIgnoreCase(pageName)) {
                loginControll.loginUser(request);
            }
        }
    }

    /**
     * Process action on Home Page module.
     */
    protected void processActionHomePage(HttpServletRequest request) {
    }
    
    /**
     * Process action on Admin Page module.
     */
    protected void processActionAdminPage(HttpServletRequest request) throws Exception {
        String subPage = request.getParameter("subPage");
        String section = request.getParameter("section");
        
        if((subPage == null) || "".equals(subPage)) {
            //Action with Admin Page index (no subpage selected)
            
        } else if(Constants.COMPANY_INFO_PAGE_NAME.equalsIgnoreCase(subPage)) {
            //Action with Company Info Page.
            
        } else if(Constants.PROJECT_MANAGEMENT_PAGE_NAME.equalsIgnoreCase(subPage)) {
            //Action with Project Management Page.
            if(Constants.PROJECT_EMPLOYEE_LIST.equalsIgnoreCase(section))
                employeeProjectController.processAction(request);
            projectController.processAction(request);            
        } else if(Constants.USER_MANAGEMENT_PAGE_NAME.equalsIgnoreCase(subPage)) {
            //Action with User Management Page.
            employeeController.processAction(request);
            
        } else if(Constants.POSITION_PAGE_NAME.equalsIgnoreCase(subPage)) {
            //Action with Position Page.
            positionController.processAction(request);
            
        } else if(Constants.PROJECT_STATUS_PAGE_NAME.equalsIgnoreCase(subPage)) {
            //Action with Project Status Page.
            projectstatusController.processAction(request);
             
        } else if(Constants.LOG_STATUS_PAGE_NAME.equalsIgnoreCase(subPage)) {
            //Action with Log Status Page.
            logStatusController.processAction(request);
            
        } else if(Constants.LOG_TYPE_PAGE_NAME.equalsIgnoreCase(subPage)) {
            //Action with Log Type Page.
            logTypeController.processAction(request);
            
        } else if(Constants.PRIORITY_PAGE_NAME.equalsIgnoreCase(subPage)) {
            //Action with Priority Page.
            priorityController.processAction(request);
            
        } else if(Constants.SEVERITY_PAGE_NAME.equalsIgnoreCase(subPage)) {
            //Action with Severity Page.
            severityController.processAction(request);
        } else if(Constants.LOGIN_ADMIN_PAGE_NAME.equalsIgnoreCase(subPage)) {
            loginControll.loginAdmin(request);
        }
    }

    /**
     * Process action on Defect Log module.
     */
    protected void processActionDefectLogPage(HttpServletRequest request) {
        String subPage = request.getParameter("subPage");
        if((subPage == null) || "".equals(subPage)) {
            
        }else {
            //Action with Defectlog Page.
            defectLogController.processAction(request);
        }
    }
    
    /**
     * Process action on Teammate module.
     */
    protected void processActionTeammatePage(HttpServletRequest request) {
    }

    /**
     * Process action on Profile module.
     */
    protected void processActionProfilePage(HttpServletRequest request) {
        controller.profileController.processAction(request);
    }

    /**
     * Show web page.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doView(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
        dispatcher.forward(request, response);
        } catch (Exception ex) {
            log.error("Error doView: " + ex.getMessage());        }
    }
    
    /**
     * Send message from Server to client.
     */
    public static void sendMessage(HttpServletRequest request, String message, boolean isError) {
        HttpSession session = request.getSession(true);
        session.setAttribute("message", message);
        
        if(isError) {
            session.setAttribute("messageType", "error");
        } else {
            session.setAttribute("messageType", "info");
        }
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (Exception ex) {
            java.util.logging.Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (Exception ex) {
            java.util.logging.Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
